﻿using System.Collections.Generic;
using System.Text;
using MidnightPeach.Engine.Packages;
using MidnightPeach.Engine.Schema;
using MidnightPeach.Engine.Schema.ServiceSchema;

namespace MidnightPeach.Engine.Generators.ServiceGenerators
{
    class ClassLoopGenerator : ServiceGenerator
    {
        public ClassLoopGenerator(Package package, Assembly assembly) : base(package)
        {
            Assembly = assembly;
        }

        public Assembly Assembly { get; private set; }

        internal override string Generate(Macro macro, string text)
        {
            List<Class> classes;

            #region 리스트를 만든다.
            switch (macro.LoopType)
            {
                case LoopType.AL:
                case LoopType.FS: // FS 특성은 더 이상 클래스에서 지원하지 않음 (하위호환을 위해 남겨둠)
                    classes = Assembly.Classes.FindAll(x => x.IsDbContext == false);
                    break;

                case LoopType.FC:
                    classes = Assembly.Classes.FindAll(x => x.ForCache);
                    break;

                case LoopType.DC:
                    classes = Assembly.Classes.FindAll(x => x.IsDbContext);
                    break;

                default:
                    throw new UnsupportedMacroException(macro, text, this);
            }
            #endregion

            StringBuilder buffer = new StringBuilder();

            for (int i = 0; i < classes.Count; i++)
            {
                string code = Build(Package, Assembly, classes[i], null, null, macro.Value);
                buffer.Append(code);

                if (i != classes.Count - 1)
                {
                    buffer.Append(macro.Seperator);
                }
            }

            return buffer.ToString();
        }
    }
}